//------------------------------------------------------------------------------
#include "CScript.h"
#include "CGlobal.h"
//------------------------------------------------------------------------------
CScript *CScript::_instance=NULL;
//------------------------------------------------------------------------------
static QScriptValue getChamp(QScriptContext *ctx, QScriptEngine *eng)
{
	if (ctx->argumentCount() != 2)
		return ctx->throwError(QObject::tr("La fonction getChamp() attend deux argument, le nom de la table et le nom du champ"));
	QString table = ctx->argument(0).toString();
	QString champ = ctx->argument(1).toString();
	QString value;
	QMainWindow *wnd=(QMainWindow *)eng->globalObject().property("wnd").toQObject();
	
	if(CGlobal::getChampValue(wnd, table, champ, value))
	{
		return QScriptValue(eng, value);
	}
	
	return QScriptValue(eng, 0);
}
//------------------------------------------------------------------------------
CScript * CScript::getInstance(void)
{		
	if(_instance == NULL)
	{	
		_instance=new CScript();
	}
	
	return _instance;
}
//------------------------------------------------------------------------------
bool CScript::isTrue(QMainWindow *wnd, QString expression)
{
	QScriptValue scriptWnd = engine->newQObject(wnd);
	bool ret;
	
	engine->globalObject().setProperty("wnd", scriptWnd);
	ret=engine->evaluate(expression).toBoolean();
	
	return ret;
}
//------------------------------------------------------------------------------
QVariant CScript::eval(QMainWindow *wnd, QString expression)
{
	QScriptValue scriptWnd = engine->newQObject(wnd);
	QVariant ret;
	
	engine->globalObject().setProperty("wnd", scriptWnd);
	ret=engine->evaluate(expression).toVariant();
	if(engine->hasUncaughtException())
	{
		ret=QVariant();
	}
	
	return ret;
}
//------------------------------------------------------------------------------
CScript::CScript()
{
	engine=new QScriptEngine();
	engine->globalObject().setProperty("getChamp", engine->newFunction(getChamp, 2));
}
//------------------------------------------------------------------------------
CScript::~CScript()
{
	delete engine;
}
//------------------------------------------------------------------------------